/**
 * @description 文档-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const fs = require('fs')
const ox = require('@daelui/oxjs')
const Service = require('./service.js')
const { explorer, filer, fileFactory, oser } = require('@daelui/oxkit')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 打开文件所在目录
  */
  openFileDir (action) {
    // 解析数据
    return this.solveAction(action).then(action => {
      // 只能本机定位至文件
      if (oser.isLocal(action.req)) {
        let path = action.params.path
        if (path) {
          path = decodeURIComponent(decodeURIComponent(path))
          explorer.openFileDir(path)
        }
        return {data: null, success: 1, status: 200}
      }
      return {data: null, success: 1, status: 403}
    })
  }

  /**
   * @function 打开文件所在目录
  */
  downloadFile (action) {
    // 解析数据
    return this.solveAction(action).then(action => {
      let path = action.params.path
      if (path) {
        path = decodeURIComponent(path)
        filer.downloadFile(path, action.req, action.res)
        // 退出
        return 'EXIT'
      }
      return {data: null, success: 1}
    })
  }

  /**
   * @function 读取文件内容
  */
  async readFile (action) {
    // 解析数据
    return this.solveAction(action).then(async action => {
      let path = action.params.path
      let data = {}
      if (path) {
        data = await fileFactory.read({ path })
      }

      // 异步结果
      if (data instanceof Promise) {
        return data.then(res => {
          return {data: {content: res.data}, success: 1}
        }).catch(res => {
          return {data: {content: res.data}, success: 0}
        })
      }

      return {data: {content: data.data}, success: 1}
    })
  }

  /**
   * @function 修改文件名称
  */
  async updateName (action) {
    // 解析数据
    return this.solveAction(action).then(async action => {
      let path = action.params.path
      let name = action.params.name
      let data = { success: 0 }
      if (path) {
        let newPath = path.replace(/[^\/\\]+$/, name)
        data = await  new Promise(function(resolve, reject){
          fs.rename(path, newPath, (e) => {
            if (e) {
              reject({ success: 0 })
            }
            resolve({ success: 1 })
          })
        })
      }

      // 异步结果
      if (data instanceof Promise) {
        return data.then(res => {
          return {data: res.data, success: 1}
        }).catch(res => {
          return {data: res.data, success: 0}
        })
      }

      return data
    })
  }
}

module.exports = Controller